import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

import java.util.Arrays;
import java.util.stream.Stream;

/**
 * 最长公共前缀
 * 题目：编写一个函数来查找字符串数组中的最长公共前缀。
 * 如果不存在公共前缀，返回空字符串 ""。
 * <p>
 * 示例1:
 * 输入: ["flower","flow","flight"]
 * 输出: "fl"
 * <p>
 * 示例2:
 * 输入: ["dog","racecar","car"]
 * 输出: ""
 * 解释: 输入不存在公共前缀。
 * <p>
 * 说明:
 * 所有输入只包含小写字母 a-z
 * <p>
 * 来源：力扣（LeetCode-14）
 * 链接：https://leetcode-cn.com/problems/longest-common-prefix
 *
 * @author godfrey
 * @since 2020-10-26
 */
@DisplayName("最长公共前缀")
public class LongestCommonPrefix extends BaseTest {

    static Stream<Arguments> testArguments() {
        return Stream.of(
                Arguments.arguments((Object) new String[]{"SBSJDCNABBCCBBAD", "ABACBCABAB", "ABC"}),
                Arguments.arguments((Object) new String[]{"ABCE", "A", "ABCDEF", "ABCEDFG"}),
                Arguments.arguments((Object) new String[]{"ABSJDCNABBCCBBAD", "ABACBCABAB", "ABC"})
        );
    }

    @DisplayName("纵向扫描-时间复杂度O(n1+n2+...)，空间复杂度O(1)")
    @ParameterizedTest
    @MethodSource("testArguments")
    void longestCommonPrefix(String[] strs) {
        if (strs.length == 0) {
            System.out.println(0);
            return;
        }

        for (int j = 0; j < strs[0].length(); ++j) {
            for (int i = 1; i < strs.length; ++i) {
                if (j == strs[i].length() || strs[i].charAt(j) != strs[0].charAt(j)) {
                    System.out.println(j == 0 ? j : strs[0].substring(0, j));
                    return;
                }
            }
        }
        System.out.println(strs[0]);
    }

    @DisplayName("横向比较-时间复杂度O(n1+n2+...)，空间复杂度O(1)")
    @ParameterizedTest
    @MethodSource("testArguments")
    void longestCommonPrefix2(String[] strs) {
        if (strs.length == 0) {
            System.out.println(0);
            return;
        }

        int rightMost = strs[0].length();
        for (int i = 1; i < strs.length; i++) {
            for (int j = 0; j < rightMost; j++)
            // 不会越界，请参考string::[]的文档
            {
                if (j == strs[i].length() || strs[i].charAt(j) != strs[0].charAt(j)) {
                    rightMost = j;
                }
            }
        }
        System.out.println(strs[0].substring(0, rightMost));
    }

    @DisplayName("两两比较-时间复杂度O(n1+n2+...)，空间复杂度O(1)")
    @ParameterizedTest
    @MethodSource("testArguments")
    void longestCommonPrefix3(String[] strs) {
        if (strs.length == 0) {
            System.out.println(0);
            return;
        }

        String ans = strs[0];
        for (int i = 1; i < strs.length; ++i) {
            int j = 0;
            for (; j < ans.length() && j < strs[i].length(); ++j) {
                if (ans.charAt(j) != strs[i].charAt(j)) {
                    break;
                }
            }
            ans = ans.substring(0, j);
            if (ans.equals("")) {
                System.out.println(0);
                return;
            }
        }
        System.out.println(ans);
    }

    @DisplayName("字典序最大和最小字符串的公共前缀-时间复杂度O(n1+n2+...)，空间复杂度O(1)")
    @ParameterizedTest
    @MethodSource("testArguments")
    void longestCommonPrefix4(String[] strs) {
        if (strs.length == 0) {
            System.out.println(0);
            return;
        }
        //字典序排序，最长公共前缀只需要比较字典序最大和最小字符串
        Arrays.sort(strs);
        String minStr = strs[0], maxStr = strs[strs.length - 1];
        for (int i = 0; i < minStr.length(); ++i) {
            if (minStr.charAt(i) != maxStr.charAt(i)) {
                System.out.println(i == 0 ? i : minStr.substring(0, i));
                return;
            }
        }
        System.out.println(minStr);
    }

    @DisplayName("分治-时间复杂度O(mn)，空间复杂度O(mlogn)")
    @ParameterizedTest
    @MethodSource("testArguments")
    void longestCommonPrefix5(String[] strs) {
        if (strs == null || strs.length == 0) {
            System.out.println(0);
            return;
        }
        System.out.println(longestCommonPrefix(strs, 0, strs.length - 1));
    }

    public String longestCommonPrefix(String[] strs, int start, int end) {
        if (start == end) {
            return strs[start];
        } else {
            int mid = (end - start) / 2 + start;
            String lcpLeft = longestCommonPrefix(strs, start, mid);
            String lcpRight = longestCommonPrefix(strs, mid + 1, end);
            return commonPrefix(lcpLeft, lcpRight);
        }
    }

    public String commonPrefix(String lcpLeft, String lcpRight) {
        int minLength = Math.min(lcpLeft.length(), lcpRight.length());
        for (int i = 0; i < minLength; i++) {
            if (lcpLeft.charAt(i) != lcpRight.charAt(i)) {
                return lcpLeft.substring(0, i);
            }
        }
        return lcpLeft.substring(0, minLength);
    }

    @DisplayName("二分查找-时间复杂度O(mn)，空间复杂度O(mlogn)")
    @ParameterizedTest
    @MethodSource("testArguments")
    void longestCommonPrefix6(String[] strs) {
        if (strs == null || strs.length == 0) {
            System.out.println(0);
            return;
        }
        int minLength = Integer.MAX_VALUE;
        for (String str : strs) {
            minLength = Math.min(minLength, str.length());
        }
        int low = 0, high = minLength;
        while (low < high) {
            int mid = (high - low + 1) / 2 + low;
            if (isCommonPrefix(strs, mid)) {
                low = mid;
            } else {
                high = mid - 1;
            }
        }
        System.out.println(strs[0].substring(0, low));
    }

    public boolean isCommonPrefix(String[] strs, int length) {
        String str0 = strs[0].substring(0, length);
        int count = strs.length;
        for (int i = 1; i < count; i++) {
            String str = strs[i];
            for (int j = 0; j < length; j++) {
                if (str0.charAt(j) != str.charAt(j)) {
                    return false;
                }
            }
        }
        return true;
    }

    @DisplayName("利用函数-时间复杂度O(a1)，空间复杂度O(1)")
    @ParameterizedTest
    @MethodSource("testArguments")
    void longestCommonPrefix7(String[] strs) {
        String ans = strs.length == 0 ? "" : strs[0];
        for (String s : strs) {
            while (!s.startsWith(ans)) {
                ans = ans.substring(0, ans.length() - 1);
            }
        }
        System.out.println(ans);;
    }
}
